#include "StackedWidgetShell.h"

StackedWidgetShell::StackedWidgetShell(QObject *parent) : QObject(parent)
{
    _stackedWidget = nullptr;
}

void StackedWidgetShell::shell(QStackedWidget *widget){
    _stackedWidget = widget;
}
void StackedWidgetShell::add(const QString &name, QWidget *widget){
    if(_nameToWidget.contains(name)){
        return;
    }
    _stackedWidget->addWidget(widget);
    _nameToWidget.insert(name,widget);
    connect(widget,&QObject::destroyed,this,&StackedWidgetShell::object_onDestoryed);
}
void StackedWidgetShell::remove(const QString &name){
    if(!_nameToWidget.contains(name)){
        return;
    }
    auto *widget = _nameToWidget.take(name);
    _stackedWidget->removeWidget(widget);
    disconnect(widget,&QObject::destroyed,this,&StackedWidgetShell::object_onDestoryed);
    widget->deleteLater();
}
bool StackedWidgetShell::contains(const QString &name){
    return _nameToWidget.contains(name);
}
void StackedWidgetShell::showWidget(const QString &name){
    if(!_nameToWidget.contains(name)){
        return;
    }
    _stackedWidget->setCurrentWidget(_nameToWidget.value(name));
}
QString StackedWidgetShell::currentWidgetName(){
    auto widget = _stackedWidget->currentWidget();
    return _nameToWidget.key(widget,"");
}

void StackedWidgetShell::object_onDestoryed(QObject *object){
    QWidget *widget = qobject_cast<QWidget*>(object);
    if(nullptr==widget){
        return;
    }
    auto key = _nameToWidget.key(widget,"");
    if(key.isEmpty()){
        return;
    }
    _nameToWidget.remove(key);
}
